{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "67df8d31",
   "metadata": {},
   "source": [
    "# 第十四周 学习笔记 函数与模块\n",
    "* 笔记内容：函数与模块\n",
    "* 记录人：蔡洪嘉\n",
    "* 时间：2021-12-02\n",
    "* Week14\n",
    "\n",
    "* 主要参考文档:\n",
    "> 1. [Python官方文档](https://python/org)\n",
    "> 2. [许老师博客](https://cnblogs.com/xuzhichao)\n",
    "\n",
    "----------"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "637a5ef7",
   "metadata": {},
   "source": [
    "# 函数\n",
    "## 函数的定义  [函数的定义](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)\n",
    "> 1. 数字：    f(x) = ax + b  \n",
    "> 2. python：   def fib(x):  \n",
    "> 3. 编程思维 VS 数学思维   \n",
    ">> 1. 函数可以被定义名称,定义的关键字 <font style=\"color:red\">***def***</font>\n",
    ">> 2. 数学思维是写在同一行（定义函数 和 运算公式），面向对象编程中 函数写多行，定义函数为单独一行\n",
    ">> 3. 数字函数一般没有注释，而编程过程中，一般需要对函数进行注释描述（docstring,课本P151）\n",
    ">> 4. 数学中：ax + b 是计算公式，而编程中，我们将函数的内容称为**函数体**，函数体要有一定的**缩进**\n",
    ">> 5. 数学函数执行，将参数带入公式，编程中函数执行，将参数带入函数体  \n",
    "## [关于函数的更多定义](https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions)\n",
    "\n",
    "> 1. 函数的参数\n",
    ">> 1. 形式参数\n",
    ">> 2. 实际参数\n",
    ">> 3. 默认参数\n",
    ">> 4. 位置参数\n",
    ">> 5. 关键字参数\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7994cfb0",
   "metadata": {},
   "source": [
    "# 函数的定义\n",
    "> 1. 定义函数\n",
    "```\n",
    "def:定义函数的关键字\n",
    "flb：函数名\n",
    "(n)：定义函数的参数\n",
    "\"\"\"  \"\"\"：文档描述 : 与使用者进行 交互的唯一途径\n",
    "代码块：\n",
    "     a, b = 0, 1\n",
    "     while a < n:\n",
    "        print(a, end=' ')\n",
    "         a, b = b, a+b\n",
    "     print()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "a7454850",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 斐波那切数列： 0 1 1 2 3 5 8 13 21 34...\n",
    "def fib(x):\n",
    "    \"\"\"列出指定x以内的斐波那切数列\"\"\"\n",
    "    a,b = 0,1\n",
    "    while a < x:\n",
    "        print(a,end=' ')\n",
    "        a,b = b, a+b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "fc0a1a22",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 1 2 3 5 8 13 21 34 55 89 "
     ]
    }
   ],
   "source": [
    "fib(100)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "380db18e",
   "metadata": {},
   "source": [
    "> 2. 调用函数/使用函数\n",
    ">> 1. 函数名(参数)\n",
    ">> 2. 参数可以不存在"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "33bec745",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好,xxx同学!\n",
      "欢迎,xxx同学!\n"
     ]
    }
   ],
   "source": [
    "# 实践：请大家写一个函数，这个函数可以打印“你好，XXX同学”\n",
    "\n",
    "def hello_user(username):    \n",
    "    print(\"你好,\"+username+\"同学!\") \n",
    "    print(\"欢迎,%s同学!\"%(username)) \n",
    "\n",
    "hello_user(\"xxx\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bfdf82b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好,Lihua同学!\n",
      "欢迎,Lihua同学!\n"
     ]
    }
   ],
   "source": [
    "hello_user(\"Lihua\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "29ccf18c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function hello_user in module __main__:\n",
      "\n",
      "hello_user(username)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(hello_user)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "51d959f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 回顾与思考\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "3f653f60",
   "metadata": {},
   "outputs": [],
   "source": [
    "# sleep() 需要给定一个时间（int）参数\n",
    "time.sleep(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "db37fe0b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function localtime in module time:\n",
      "\n",
      "localtime(...)\n",
      "    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n",
      "                              tm_sec,tm_wday,tm_yday,tm_isdst)\n",
      "    \n",
      "    Convert seconds since the Epoch to a time tuple expressing local time.\n",
      "    When 'seconds' is not passed in, convert the current time instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(time.localtime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "20c0a05f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "time.struct_time(tm_year=2021, tm_mon=12, tm_mday=2, tm_hour=10, tm_min=46, tm_sec=58, tm_wday=3, tm_yday=336, tm_isdst=0)"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# localtime() 不需要给定参数\n",
    "time.localtime()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c0072cd",
   "metadata": {},
   "source": [
    "> 3.函数的优势\n",
    ">> 1. 可以重复使用相同的功能，避免重复造轮子\n",
    ">> 2. 使用者可以不了解函数本身，只需要清楚如何使用即可\n",
    ">> 3. 使用/调用方便，只需要清楚传递的 函数名及参数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19a987e2",
   "metadata": {},
   "source": [
    "# 函数的参数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6cb3de6",
   "metadata": {},
   "source": [
    "> 1. 形式参数（形参）\n",
    ">> 1. 在**定义**函数的时候定义的参数\n",
    ">> 2. 形式参数不占用内存\n",
    "> 2. 实际参数（实参）\n",
    ">> 1. 在**调用**函数的时候传递的参数\n",
    ">> 2. 调用函数时，形式参数分配空间，传递实际参数，执行函数内容\n",
    "\n",
    "| 名字 | 介绍 |\n",
    "| :---: | :---: |\n",
    "|形参：|形式参数，不是实际存在的，是虚拟变量。在定义函数和函数体的时候使用形参，目的是在函数调用时接收实参。|\n",
    "|实参：|实际参数，调用函数时传递给函数的参数，可以是常量、变量，表达式，函数，传给形参。|\n",
    "|区别：|形参是虚拟的，不占用空间，形参变量只有在被调用时才分配内存单元，实参是一个变量，占用内存空间，数据传递单向，实参传给形参，不能倒过来。|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bbeb0d4",
   "metadata": {},
   "source": [
    "*  课本函数实践案例\n",
    "```\n",
    "def search4vowels(word):\n",
    "    \"\"\"显示文本中出现的元音字母有哪些\"\"\"\n",
    "    vowels = set(\"aeiou\")\n",
    "    word = set(word)\n",
    "    print(vowels & word)\n",
    "```\n",
    "> 1. 形式参数： word\n",
    "> 2. 实际参数：\"fbheduigpewjiewmcfkdlaepw\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "644a4a70",
   "metadata": {},
   "outputs": [],
   "source": [
    "def hello(name):\n",
    "    \"\"\"显示问候语\"\"\"\n",
    "    print(\"你好，%s同学~\"%(name))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "79460107",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function hello in module __main__:\n",
      "\n",
      "hello(name)\n",
      "    显示问候语\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(hello)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "75072532",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 课本函数实际案例\n",
    "def search4vowels(word):\n",
    "    \"\"\"\n",
    "    显示文本中出现的元音字母有哪些\n",
    "    woed是文本信息，请输入正确的文本给word\n",
    "    \"\"\"\n",
    "    vowels = set(\"aeiou\")\n",
    "    word = set(word)\n",
    "    print(vowels & word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "d434219f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function search4vowels in module __main__:\n",
      "\n",
      "search4vowels(word)\n",
      "    显示文本中出现的元音字母有哪些\n",
      "    woed是文本信息，请输入正确的文本给word\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(search4vowels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "ac89421b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'e', 'i', 'o', 'u'}\n"
     ]
    }
   ],
   "source": [
    "search4vowels(\"qwertyuioplkjhgfdszxcvbnm\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "978e2823",
   "metadata": {},
   "source": [
    "* 在多个参数的情境下\n",
    "\n",
    "> 1. 位置参数\n",
    ">> 1. 在形式参数的定义中，有一定的先后顺序\n",
    ">> 2. 在调用函数时，要考虑形参的先后顺序\n",
    ">> 3. 调用函数时，不仅要考虑参数位置，还需要考虑形式参数的个数\n",
    "> 2. 关键字参数  \n",
    ">> 1. 在调用函数时，关键字参数可以不考虑形式参数的位置\n",
    "> 3. 默认参数  \n",
    ">> 1. 调用函数时，可以省略传递的参数信息\n",
    ">> 2. 调用函数时，如果给默认参数赋值，会替换默认参数的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "2407ee80",
   "metadata": {},
   "outputs": [],
   "source": [
    "def describe_pet(animal_type,pet_name):\n",
    "    \"\"\"显示宠物信息\"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My\" + animal_type + \"'s name is \"+pet_name.title() + \".\")\n",
    "\n",
    "#函数调用多次是一种效率极高的工作方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "d89a8989",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a dog.\n",
      "Mydog's name is 豆豆.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(\"dog\",\"豆豆\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "4718e9ce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a dog.\n",
      "Mydog's name is 豆豆.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(animal_type=\"dog\",pet_name=\"豆豆\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61e0c288",
   "metadata": {},
   "source": [
    "-------------\n",
    "* 参数注意事项实践\n",
    "> 1. 位置参数和关键字参数同时使用（调用函数）\n",
    ">> 1. positional argument follows keyword argument（关键字参数<font style=\"color:red\">均</font>应该放在位置参数之后）\n",
    ">> 2. <font style=\"color:red\">只要满足1的条件，剩余的关键字参数（多个）不考虑先后顺序</font>\n",
    "> 2. 非默认参数和默认参数同时使用（定义函数）\n",
    ">> 1. non-default argument follows default argument（默认参数<font style=\"color:red\">均</font>应该放在非默认参数之后）\n",
    ">> 2. <font style=\"color:red\">只要满足1的条件，剩余的关键字参数（多个）不考虑先后顺序</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "cf4d5ac4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test(x,y,z):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "17f15795",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "positional argument follows keyword argument (<ipython-input-66-489fdb94d38c>, line 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-66-489fdb94d38c>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m    test(5,y=3,2)\u001b[0m\n\u001b[1;37m               ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n"
     ]
    }
   ],
   "source": [
    "# 实践1：\n",
    "test(5,y=3,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "3e3da344",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "3\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "# 实践2：\n",
    "test(5,3,z = 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "ef057648",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "# 实践3：\n",
    "test(5,z=3,y=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "870a75b1",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "non-default argument follows default argument (<ipython-input-63-5faa3a0fbd68>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-63-5faa3a0fbd68>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    def test(x,y=1,z):\u001b[0m\n\u001b[1;37m             ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m non-default argument follows default argument\n"
     ]
    }
   ],
   "source": [
    "def test(x,y=1,z):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "2628caba",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test(x,z,y=1):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c0c4e18",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
